import debounce from 'lodash.debounce';
import union from 'lodash.union';
import React  from 'react';
import PropTypes from 'proptypes';
import ReactDOM from 'react-dom';
import { useParams } from 'react-router-dom';
import { connect } from 'react-redux';
import { Tab, Tabs, TabList, TabPanel } from 'react-tabs';
import * as ConnActions from '../actions/connections.js';
import * as QueryActions from '../actions/queries';
import * as DbAction from '../actions/databases';
import * as EditActions from '../reducers/tableEdit';
import { fetchTablesIfNeeded, selectTablesForDiagram } from '../actions/tables';
import { fetchSchemasIfNeeded } from '../actions/schemas';
import { fetchTableColumnsIfNeeded } from '../actions/columns';
import { fetchTableTriggersIfNeeded } from '../actions/triggers';
import { fetchTableIndexesIfNeeded } from '../actions/indexes';
import { fetchViewsIfNeeded } from '../actions/views';
import { fetchRoutinesIfNeeded } from '../actions/routines';
import { getSQLScriptIfNeeded } from '../actions/sqlscripts';
import { fetchTableKeysIfNeeded } from '../actions/keys';
import DatabaseFilter from '../components/database-filter.jsx';
import DatabaseList from '../components/database-list.jsx';
import DatabaseDiagramModal from '../components/database-diagram-modal.jsx';
import Header from '../components/header.jsx';
import Footer from '../components/footer.jsx';
import Query from '../components/query.jsx';
import Loader from '../components/loader.jsx';
import PromptModal from '../components/prompt-modal.jsx';
// import MenuHandler from '../../menu-handler';
import { requireLogos } from '../components/require-context';
import ModalEdit from './ModalEdit';
import { withStyles } from '@mui/styles';
import Toolbar from '@mui/material/Toolbar';
import AppBar from '@mui/material/AppBar';
import Typography from '@mui/material/Typography';
import StorageIcon from '@mui/icons-material/Storage';

import IconButton from '@mui/material/IconButton';
import PowerIcon from '@mui/icons-material/Power';
import PowerCloseIcon from '@mui/icons-material/PowerSettingsNew';
import {useNavigate} from 'react-router-dom'
// =======
// import Button from '@mui/material/Button';
// import PowerIcon from '@mui/icons-material/Power';
// import PowerCloseIcon from '@mui/icons-material/PowerSettingsNew';
// >>>>>>> a641ed1413703f27be0fb5a3de959c86abc08fa1
const LOGO_PATH = './logo-128px.png';
var { sqlectron } = window.myremote; //
const styles = theme => ({
  grow: {
    flexGrow: 1,
  },
});
const tab_title_h = '45px';
const SIDEBAR_WIDTH = 235;
const STYLES = {
  wrapper: {},
  container: {
    display: 'flex',
    boxSizing: 'border-box',
    padding: '0px 10px 0px 10px',
  },
  sidebar: {
    transition: 'all .2s',
  },
  content: { flex: 1, overflow: 'auto', paddingLeft: '5px' },
  collapse: {
    position: 'fixed',
    color: '#fff',
    cursor: 'pointer',
    width: 10,
    left: 0,
    height: '100vh',
    backgroundColor: 'rgb(102,102,102)',
    zIndex: 1,
    MozUserSelect: 'none',
    WebkitUserSelect: 'none',
    msUserSelect: 'none',
  },
  resizeable: { width: 'auto', maxWidth: '100%' },
};

const CLIENTS = sqlectron.db.CLIENTS.reduce((clients, dbClient) => {
  /* eslint no-param-reassign:0 */
  clients[dbClient.key] = {
    title: dbClient.name,
    image: requireLogos(dbClient.key),
  };
  return clients;
}, {});

function QueryBrowserContainer(props){
  let navigate=useNavigate();
  let params=useParams();
  const [state,setState]=React.useState({
    tabNavPosition: 0,
    sideBarWidth: SIDEBAR_WIDTH,
    sidebarCollapsed: false,
  });
  // constructor(props, context) {
  //   super(props, context);
  //   state = {
  //     tabNavPosition: 0,
  //     sideBarWidth: SIDEBAR_WIDTH,
  //     sidebarCollapsed: false,
  //   };
  //   menuHandler = new MenuHandler();
  // }

  // menuHandler = new MenuHandler();
  const ref_tabInput=React.useRef(null);
  const ref_databaseList=React.useRef(null);
  const ref_databaseFilter=React.useRef(null);
  React.useEffect(()=>{
    console.log(props)
    const { dispatch} = props;
    dispatch(ConnActions.connect(params.id));
  },[props.match]);
  React.useEffect(()=>{
    setMenus()
  },[]);
  React.useEffect(()=>{
    const { dispatch, history, connections } = props;
    if (!connections.connected) {
      return;
    }
    const lastConnectedDB =
    connections.databases[connections.databases.length - 1];
    const filter = connections.server.filter;

    dispatch(DbAction.fetchDatabasesIfNeeded(filter));
    dispatch(fetchSchemasIfNeeded(lastConnectedDB));
    dispatch(fetchTablesIfNeeded(lastConnectedDB, filter));
    dispatch(fetchViewsIfNeeded(lastConnectedDB, filter));
    dispatch(fetchRoutinesIfNeeded(lastConnectedDB, filter));

    setMenus();
    return ()=>{
      // menuHandler.removeAllMenus();
    }
  },[props.connections]);
  // UNSAFE_componentWillReceiveProps(nextProps) {

  //   const { dispatch, history, connections } = nextProps;

  //   if (!connections.connected) {
  //     return;
  //   }

  //   const lastConnectedDB =
  //   connections.databases[connections.databases.length - 1];
  //   const filter = connections.server.filter;

  //   dispatch(DbAction.fetchDatabasesIfNeeded(filter));
  //   dispatch(fetchSchemasIfNeeded(lastConnectedDB));
  //   dispatch(fetchTablesIfNeeded(lastConnectedDB, filter));
  //   dispatch(fetchViewsIfNeeded(lastConnectedDB, filter));
  //   dispatch(fetchRoutinesIfNeeded(lastConnectedDB, filter));

  //   setMenus();
  // }

  // componentDidUpdate() {
  //   const elem = ReactDOM.findDOMNode(refs.tabList);
  //   if (!elem) {
  //     return;
  //   }

  //   tabListTotalWidth = elem.offsetWidth;
  //   tabListTotalWidthChildren = 0;
  //   for (const child of elem.children) {
  //     tabListTotalWidthChildren += child.offsetWidth;
  //   }
  // }

  // componentWillUnmount() {
  //   menuHandler.removeAllMenus();
  // }

  const onSelectDatabase=(database)=> {
    const { dispatch, params } = props;

    dispatch(ConnActions.connect(params.id, database.name));
  }

  const onExecuteDefaultQuery=(database, table)=> {
    const schema = table.schema || props.connections.server.schema;
    props.dispatch(
      QueryActions.executeDefaultSelectQueryIfNeeded(
        database.name,
        table.name,
        schema
      )
    );
  }

  const onCollapseClick = () => {
    setState((state)=>({...state,sidebarCollapsed: !state.sidebarCollapsed }));
  };

  const onPromptCancelClick=() =>{
    const { dispatch } = props;
    dispatch(ConnActions.disconnect());
  }

  const onPromptOKClick=(password)=> {
    const { dispatch, params } = props;
    dispatch(ConnActions.connect(params.id, null, false, password));
  }

  const onSelectTable=(database, table)=> {
    const schema = table.schema || props.connections.server.schema;
    props.dispatch(
      fetchTableColumnsIfNeeded(database.name, table.name, schema)
    );
    props.dispatch(
      fetchTableTriggersIfNeeded(database.name, table.name, schema)
    );
    props.dispatch(
      fetchTableIndexesIfNeeded(database.name, table.name, schema)
    );
  }

  const onGetSQLScript=(database, item, actionType, objectType)=> {
    const schema = item.schema || props.connections.server.schema;
    props.dispatch(
      getSQLScriptIfNeeded(
        database.name,
        item.name,
        actionType,
        objectType,
        schema
      )
    );
  }

  const onSQLChange=(sqlQuery)=> {
    console.log("onSQLChange");
    props.dispatch(QueryActions.updateQueryIfNeeded(sqlQuery));
  }

  const onQuerySelectionChange=(sqlQuery, selectedQuery) =>{
    props.dispatch(
      QueryActions.updateQueryIfNeeded(sqlQuery, selectedQuery)
    );
  }

  const onFilterChange=(value)=> {
    setState((state)=>({...state, filter: value }));
  }

  const onCloseConnectionClick=() =>{
    const { dispatch } = props;
    dispatch(ConnActions.disconnect());
    navigate('/');
  }

  const onReConnectionClick=()=> {
    const { dispatch, params } = props;
    dispatch(ConnActions.reconnect(params.id, getCurrentQuery().database));
  }

  const onRefreshDatabase=(database) =>{
    const { dispatch } = props;
    dispatch(DbAction.refreshDatabase(database));
  }

  const onShowDiagramModal=(database) =>{
    const { dispatch } = props;
    dispatch(DbAction.showDatabaseDiagram(database.name));
  }

  const onGenerateDatabaseDiagram=(database, selectedTables) =>{
    const { dispatch } = props;
    //const selectedTables = [];

    dispatch(DbAction.generateDatabaseDiagram());
    //todo
    // $(':checkbox:checked', 'div.ui.list')
    //   .map((index, checkbox) => selectedTables.push(checkbox.id));

    dispatch(selectTablesForDiagram(selectedTables));
    fetchTableDiagramData(database, selectedTables);
  }

  const onAddRelatedTables=(relatedTables)=> {
    const { dispatch, databases, tables } = props;
    const database = databases.diagramDatabase;
    const tablesOnDiagram = tables.selectedTablesForDiagram;
    const selectedTables = union(tablesOnDiagram, relatedTables);

    dispatch(selectTablesForDiagram(selectedTables));
    fetchTableDiagramData(database, relatedTables);
  }

  const onSaveDatabaseDiagram=(diagram) =>{
    props.dispatch(DbAction.saveDatabaseDiagram(diagram));
  }

  const onExportDatabaseDiagram=(diagram, imageType)=> {
    props.dispatch(DbAction.exportDatabaseDiagram(diagram, imageType));
  }

  const onOpenDatabaseDiagram=()=> {
    props.dispatch(DbAction.openDatabaseDiagram());
  }

  const onCloseDiagramModal=()=> {
    console.log("close");
    props.dispatch(DbAction.closeDatabaseDiagram());
  }

  const onTabDoubleClick=(queryId) =>{
    setState((state)=>({...state, renamingTabQueryId: queryId }));
  }

  const getCurrentQuery=()=> {
    return props.queries.queriesById[props.queries.currentQueryId];
  }

  const setMenus=()=> {
    // menuHandler.setMenus({
    //   'sqlectron:query-execute': () => {
    //     const {
    //       queries: { queriesById, currentQueryId },
    //     } = props;
    //     const currentQuery = queriesById[currentQueryId];
    //     handleExecuteQuery(
    //       currentQuery.selectedQuery || currentQuery.query
    //     );
    //   },
    //   'sqlectron:new-tab': () => newTab(),
    //   'sqlectron:close-tab': () => closeTab(),
    //   'sqlectron:save-query': () => saveQuery(),
    //   'sqlectron:open-query': () => openQuery(),
    //   'sqlectron:query-focus': () => focusQuery(),
    //   'sqlectron:toggle-database-search': () => toggleDatabaseSearch(),
    //   'sqlectron:toggle-database-objects-search': () =>
    //     toggleDatabaseObjectsSearch(),
    // });
  }

  const fetchTableDiagramData=(database, tables) =>{
    const { dispatch, connections } = props;
    tables.forEach(item => {
      const schema = item.schema || connections.server.schema;
      dispatch(fetchTableColumnsIfNeeded(database, item, schema));
      dispatch(fetchTableKeysIfNeeded(database, item, schema));
    });
  }

  const handleSelectTab=(index)=> {
    const queryId = props.queries.queryIds[index];
    props.dispatch(QueryActions.selectQuery(queryId));
  }

  const removeQuery=(queryId) =>{
    props.dispatch(QueryActions.removeQuery(queryId));
  }

  const saveQuery=() =>{
    props.dispatch(QueryActions.saveQuery());
  }

  const openQuery=() =>{
    props.dispatch(QueryActions.openQuery());
  }

  const copyToClipboard = (rows, type) => {
    //console.log(rows);
    //console.log(type);
    props.dispatch(QueryActions.copyToClipboard(rows, type));
  };

  const saveToFile=(rows, type)=> {
    props.dispatch(QueryActions.saveToFile(rows, type));
  }

  const handleExecuteQuery=(sqlQuery) =>{
    const currentQuery = getCurrentQuery();
    if (!currentQuery) {
      return;
    }

    props.dispatch(
      QueryActions.executeQueryIfNeeded(sqlQuery, currentQuery.id)
    );
  }

  const handleCancelQuery=()=> {
    const currentQuery = getCurrentQuery();
    if (!currentQuery) {
      return;
    }

    props.dispatch(QueryActions.cancelQuery(currentQuery.id));
  }

  const filterDatabases=(name, databases) =>{
    const regex = RegExp(name, 'i');
    // console.log("filterDatabases");
    // console.log(databases.length);

    return databases.filter(db => regex.test(db.name));
  }

  const focusQuery=()=> {
    const currentQuery = getCurrentQuery();
    if (!currentQuery) {
      return;
    }

    // refs[`queryBox_${currentQuery.id}`].focus();
  }

  const toggleDatabaseSearch=()=> {
    ref_databaseFilter.current.focus();
  }

  const toggleDatabaseObjectsSearch=()=> {
    const currentDB = getCurrentQuery().database;
    if (!currentDB) {
      return;
    }

    ref_databaseList.current.focus(currentDB);
  }

  const newTab=()=> {
    props.dispatch(QueryActions.newQuery(getCurrentQuery().database));
  }
  const onExecuteEditTable = (database, item) => {
    // console.log("onExecuteEditTable");
    props.dispatch({
      type: EditActions.SHOW_EDIT,
      database: database,
      item: item,
    });
  };
  const closeTab=()=> {
    removeQuery(props.queries.currentQueryId);
  }

  const renderDatabaseDiagramModal=()=> {
    const { databases, tables, columns, views, keys } = props;

    const selectedDB = databases.diagramDatabase;

    return (
      <DatabaseDiagramModal
        modalOpen={props.databases.showingDiagram}
        database={selectedDB}
        tables={tables.itemsByDatabase[selectedDB]}
        selectedTables={tables.selectedTablesForDiagram}
        views={views.viewsByDatabase[selectedDB]}
        columnsByTable={columns.columnsByTable[selectedDB]}
        tableKeys={keys.keysByTable[selectedDB]}
        diagramJSON={databases.diagramJSON}
        isSaving={databases.isSaving}
        onGenerateDatabaseDiagram={onGenerateDatabaseDiagram}
        addRelatedTables={onAddRelatedTables}
        onSaveDatabaseDiagram={onSaveDatabaseDiagram}
        onExportDatabaseDiagram={onExportDatabaseDiagram}
        onOpenDatabaseDiagram={onOpenDatabaseDiagram}
        onClose={onCloseDiagramModal}
      />
    );
  }

  const renderTabQueries=()=> {
    const {
      dispatch,
      connections,
      queries,
      databases,
      schemas,
      tables,
      columns,
      triggers,
      indexes,
      views,
      routines,
    } = props;

    const currentDB = getCurrentQuery().database;

    const menu = queries.queryIds.map(queryId => {
      //const isCurrentQuery = queryId === queries.currentQueryId;
      const buildContent = () => {
        const isRenaming = state.renamingTabQueryId === queryId;
        if (isRenaming) {
          return (
            <div className="ui input">
              <input
                autoFocus
                type="text"
                ref={ref_tabInput}
                onBlur={() => {
                  dispatch(QueryActions.renameQuery(ref_tabInput.current.value));
                  setState((state)=>({...state, renamingTabQueryId: null }));
                }}
                onKeyDown={event => {
                  if (event.key !== 'Escape' && event.key !== 'Enter') {
                    return;
                  }

                  if (event.key === 'Enter') {
                    dispatch(QueryActions.renameQuery(ref_tabInput.current.value));
                  }

                  setState((state)=>({...state, renamingTabQueryId: null }));
                }}
                defaultValue={queries.queriesById[queryId].name}
              />
            </div>
          );
        }
        //return queries.queriesById[queryId].name;
        var names = queries.queriesById[queryId].name.split('/');
        var name = names[names.length - 1];
        return (
          <div style={{ display: 'flex', height: tab_title_h }}>
            {name}
            <PowerCloseIcon
              onClick={debounce(() => {
                removeQuery(queryId);
                const position = state.tabNavPosition + 200;
                setState((state)=>({...state, tabNavPosition: position > 0 ? 0 : position }));
              }, 200)}
            > 
            </PowerCloseIcon>
          </div>
        );
      };

      return (
        <Tab key={queryId} onDoubleClick={() => onTabDoubleClick(queryId)}>
          {buildContent()}
        </Tab>
      );
    });

    const { disabledFeatures } = sqlectron.db.CLIENTS.find(
      dbClient => dbClient.key === connections.server.client
    );

    const allowCancel =
      !disabledFeatures || !~disabledFeatures.indexOf('cancelQuery');
    var offset;
    if (state.sidebarCollapsed) {
      offset = 0;
    } else {
      offset = state.sideBarWidth;
    }
    const panels = queries.queryIds.map(queryId => {
      const query = queries.queriesById[queryId];

      return (
        <TabPanel key={queryId}>
          <Query
            editorName={`querybox${queryId}`}
            client={connections.server.client}
            allowCancel={allowCancel}
            query={query}
            enabledAutoComplete={queries.enabledAutoComplete}
            enabledLiveAutoComplete={queries.enabledLiveAutoComplete}
            database={currentDB}
            databases={databases.items}
            schemas={schemas.itemsByDatabase[query.database]}
            tables={tables.itemsByDatabase[query.database]}
            columnsByTable={columns.columnsByTable[query.database]}
            triggersByTable={triggers.triggersByTable[query.database]}
            indexesByTable={indexes.indexesByTable[query.database]}
            views={views.viewsByDatabase[query.database]}
            functions={routines.functionsByDatabase[query.database]}
            procedures={routines.proceduresByDatabase[query.database]}
            widthOffset={offset}
            onExecQueryClick={handleExecuteQuery}
            onCancelQueryClick={handleCancelQuery}
            onCopyToClipboardClick={copyToClipboard}
            onSaveToFileClick={saveToFile}
            onSQLChange={onSQLChange}
            onSelectionChange={onQuerySelectionChange}
          />
        </TabPanel>
      );
    });

    // const isOnMaxPosition = (
    //   tabListTotalWidthChildren - Math.abs(state.tabNavPosition) <= tabListTotalWidth
    // );
    const selectedIndex = queries.queryIds.indexOf(queries.currentQueryId);
    //const isTabsFitOnScreen = (tabListTotalWidthChildren >= tabListTotalWidth);
    return (
      <Tabs
        onSelect={handleSelectTab}
        selectedIndex={selectedIndex}
        forceRenderTabPanel
      >
        {
          // <div id="tabs-nav-wrapper" className="ui pointing secondary menu">
          //   {isTabsFitOnScreen &&
          //     <Button className="ui icon Button"
          //       disabled={state.tabNavPosition === 0}
          //       onClick={() => {
          //         const position = state.tabNavPosition + 100;
          //         setState({ tabNavPosition: position > 0 ? 0 : position });
          //       }}>
          //       <i className="left chevron icon"></i>
          //     </Button>
          //   }
          //   <div style={{flex: "auto",overFlow: "hidden"}} >
        }
        <TabList
          style={{
            display: 'flex',
            height: tab_title_h,
            overflowX: 'auto',
            overflowY: 'hidden',
          }}
        >
          {menu}
        </TabList>
        {
          //   </div>
          //   <Button className="ui basic icon Button" onClick={() => newTab()}>
          //     <i className="plus icon"></i>
          //   </Button>
          //   {isTabsFitOnScreen &&
          //     <Button className="ui icon Button"
          //       disabled={tabListTotalWidthChildren < tabListTotalWidth || isOnMaxPosition}
          //       onClick={() => {
          //         const position = state.tabNavPosition - 100;
          //         setState({ tabNavPosition: position });
          //       }}>
          //       <i className="right chevron icon"></i>
          //     </Button>
          //   }
          // </div>
        }
        {panels}
      </Tabs>
    );
  }

  // render() {
    console.log("render query-browser==========================");
    console.log(state,props);
    const { filter } = state;
    const {
      status,
      connections,
      databases,
      schemas,
      tables,
      columns,
      triggers,
      indexes,
      views,
      routines,
    } = props;
    const currentDB = getCurrentQuery()
      ? getCurrentQuery().database
      : null;
    if (connections.waitingPrivateKeyPassphrase) {
      return (
        <PromptModal
          modalOpen={connections.waitingPrivateKeyPassphrase}
          type="password"
          title={'SSH Private Key Passphrase'}
          message="Enter the private key passphrase:"
          onCancelClick={onPromptCancelClick}
          onOKClick={onPromptOKClick}
        />
      );
    }

    const isLoading = !connections.connected;
    if (isLoading && (!connections.server || !getCurrentQuery())) {
      return <Loader message={status} type="page" />;
    }

    // const breadcrumb = connections.server
    //   ? [
    //       { icon: 'server', label: connections.server.name },
    //       { icon: 'database', label: getCurrentQuery().database },
    //     ]
    //   : [];

    const filteredDatabases = filterDatabases(filter, databases.items);
    console.log("query-browser render===================")
    console.log(props,state)
    return (
      <div style={STYLES.wrapper}>
        {isLoading && <Loader message={status} type="page" />}
        {props.tableEdit.show_edit && (
          <ModalEdit
            modalOpen={props.tableEdit.show_edit}
            handleClose={() => {
              props.dispatch({ type: EditActions.HIDE_EDIT });
            }}
            database={props.tableEdit.database}
            item={props.tableEdit.item}
          />
        )}
        <AppBar position="static">
          <Toolbar>
            <img alt="logo" src={LOGO_PATH} style={{ width: '5.5em' }} />
            <StorageIcon />
            <Typography
              variant="h6"
              color="inherit"
              className={props.classes.grow}
            >
              {connections.server.name}
              {getCurrentQuery().database}
            </Typography>
            <IconButton
              color="inherit"
              variant="contained"
              title="Reconnect"
              onClick={onReConnectionClick}
            >
              <PowerIcon />
            </IconButton>
            <IconButton
              variant="contained"
              color="inherit"
              title="Close connection"
              onClick={onCloseConnectionClick}
            >
               <PowerCloseIcon />
            </IconButton>
          </Toolbar>
        </AppBar>
        <div onClick={onCollapseClick} style={STYLES.collapse}>
          <i
            className={`${
              state.sidebarCollapsed ? 'right' : 'left'
            } triangle icon`}
            style={{
              top: 'calc(100vh/2 - 7px)',
              position: 'absolute',
              marginLeft: -3,
            }}
          />
        </div>
        <div style={STYLES.container}>
          <div
            id="sidebar"
            style={{
              ...STYLES.sidebar,
              width:state.sideBarWidth,
              marginLeft: state.sidebarCollapsed
                ? -state.sideBarWidth
                : 0,
            }}
          >
             <div className="ui vertical menu" style={STYLES.resizeable}>
                <div className="item active" style={{ textAlign: 'center' }}>
                  <b>{connections.server.name}</b>
                  <img
                    title={CLIENTS[connections.server.client].name}
                    alt={CLIENTS[connections.server.client].name}
                    style={{ width: '2.5em' }}
                    className="ui mini left spaced image right"
                    src={CLIENTS[connections.server.client].image}
                  />
                </div>
                  <div className="item">
                    <DatabaseFilter
                      ref={ref_databaseFilter}
                      value={filter}
                      isFetching={databases.isFetching}
                      onFilterChange={onFilterChange} />
                  </div>
                <DatabaseList
                  ref={ref_databaseList}
                  client={connections.server.client}
                  databases={filteredDatabases}
                  currentDB={currentDB}
                  isFetching={databases.isFetching}
                  schemasByDatabase={schemas.itemsByDatabase}
                  tablesByDatabase={tables.itemsByDatabase}
                  columnsByTable={columns.columnsByTable}
                  triggersByTable={triggers.triggersByTable}
                  indexesByTable={indexes.indexesByTable}
                  viewsByDatabase={views.viewsByDatabase}
                  functionsByDatabase={routines.functionsByDatabase}
                  proceduresByDatabase={routines.proceduresByDatabase}
                  onSelectDatabase={onSelectDatabase}
                  onExecuteDefaultQuery={onExecuteDefaultQuery}
                  onExecuteEditTable={onExecuteEditTable}
                  onSelectTable={onSelectTable}
                  onGetSQLScript={onGetSQLScript}
                  onRefreshDatabase={onRefreshDatabase}
                  onShowDiagramModal={onShowDiagramModal}
                />
              </div>
          </div>
          <div style={STYLES.content}>{renderTabQueries()}</div>
          {props.databases.showingDiagram &&
            renderDatabaseDiagramModal()}
        </div>
        {
          <div style={STYLES.footer}>
            <Footer status={status} />
          </div>
        }
      </div>
    );
}

function mapStateToProps(state) {
  // console.log("mapStateToProps");
  // console.log(state)
  const {
    connections,
    databases,
    schemas,
    tables,
    columns,
    triggers,
    indexes,
    views,
    routines,
    queries,
    sqlscripts,
    keys,
    status,
    tableEdit,
  } = state;

  return {
    connections,
    databases,
    schemas,
    tables,
    columns,
    triggers,
    indexes,
    views,
    routines,
    queries,
    sqlscripts,
    keys,
    status,
    tableEdit,
  };
}

export default connect(mapStateToProps)(withStyles(styles)(QueryBrowserContainer));
